$(function() {
    //从缓存中获取数据（在登录成功后会将当前用户和用户令牌放入缓存中）
    const user = JSON.parse(window.sessionStorage.getItem("user"));
    const token = window.sessionStorage.getItem("token");
    if(user == null || token == null){
        alert("请先登录");
        window.location.href = "../html/welcome.html";
    }

    //初始化第一页内容
    pageUserAjax(token,1);

    //为底部分页框添加分页方法
    $("#userPageSelect").change(function(){
        pageUserAjax(token,$(this).children('option:selected').val());
    });

    //点击添加用户时先清空弹出的添加用户框的内容
    $("#outAddUserBtn").click(function (){
        $("#addUsername").val("");
        $("#addPassword").val("");
        $("#addSex").find('option[value="男"]').prop('selected',true);
        $("#addBirthday").val("");
        $("#addPhone").val("");
        $("#addEmail").val("");
    });

    //给添加用户弹窗的添加按钮添加点击事件
    $("#addUserBtn").click(function (){
        const username = $("#addUsername").val();
        const password = $("#addPassword").val();
        const sex = $("#addSex").children('option:selected').val();
        const birthday = $("#addBirthday").val();
        const phone = $("#addPhone").val();
        const email = $("#addEmail").val();
        // console.log("birthday:" + birthday);
        const user = new AddUser(username,password,sex,birthday,phone,email);
        addUserAjax(token,user);
    });

    //进行修改操作的userId
    let updateUserId = null;
    //修改前的用户名
    let beforeUsername = null;
    //给修改用户按钮添加点击事件
    for (let i = 1; i <= 10; i++) {
        $("#updateUserBtn" + i).click(function (){
            updateUserId = null;
            updateUserId = $("#userId" + i).html();
            beforeUsername = $("#username" + i).html();
            if(beforeUsername == "/"){
                getOneUserAjax(token,"");
            }else {
                getOneUserAjax(token,beforeUsername);
            }
        });
    }
    //给弹出的修改用户窗口的保存按钮添加点击事件
    $("#updateUserBtn").click(function (){
        const updateUsername = $("#updateUsername").val();
        const updatePassword = $("#updatePassword").val();
        const updateSex = $("#updateSex").children('option:selected').val();
        const updateBirthday = $("#updateBirthday").val();
        const updatePhone = $("#updatePhone").val();
        const updateEmail = $("#updateEmail").val();

        const updateUser = new User(updateUserId,updateUsername,updatePassword,updateSex,updateBirthday,updatePhone,updateEmail);
        if(beforeUsername !== updateUsername){
            updateUserAjax(token,updateUser,true);
        }else {
            updateUserAjax(token,updateUser,false);
        }
    });


    //进行删除操作的userId
    let deleteUserId = null;
    //给删除用户按钮添加点击事件
    for (let i = 1; i <= 10; i++) {
        $("#deleteUserBtn"+i).click(function (){
            deleteUserId = null;
            deleteUserId = $("#userId"+i).html();
        });
    }
    //给确认删除按钮添加点击事件
    $("#deleteUserBtn").click(function (){
        deleteUserAjax(token,deleteUserId);
    });

    //给修改管理员密码按钮添加点击事件
    $("#saveNewPasswordBtn").click(function (){
        const oldPassword = $("#oldPassword").val();
        const newPassword = $("#newPassword").val();
        const reNewPassword = $("#reNewPassword").val();
        if(newPassword !== reNewPassword){
            spop({
                template: "两次密码不匹配",
                position  : 'top-center',
                group: "submit-satus",
                style: "fail",
                autoclose: 2000
            });
        }else {
            updateAdminPassword(token,oldPassword,newPassword);
        }
    });

    //给查询用户按钮添加点击事件
    $("#searchUserBtn").click(function (){
        const searchUsername = $("#searchUsername").val();
        console.log("searchUsername"+searchUsername);
        searchByUsernameAjax(token,searchUsername);
    });

    //关闭页面时调用logout方法，退出当前登录用户
    $(window).unload(function(){
        $.ajax({
            type:"POST",
            contentType:"application/json",
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            url :"http://localhost:2082/logout?username=" + user.username
        })
    });

});


//用户对象
function User(userId,username,password,sex,birthday,phone,email) {
    this.userId = userId;
    this.username = username;
    this.password = password;
    this.sex = sex;
    this.birthday = birthday;
    this.phone = phone;
    this.email = email;
}

//添加用户对象
function AddUser(username,password,sex,birthday,phone,email) {
    this.username = username;
    this.password = password;
    this.sex = sex;
    this.birthday = birthday;
    this.phone = phone;
    this.email = email;
}

//分页获取用户信息ajax
function pageUserAjax(token,current){
    $.ajax({
        type: "GET",
        contentType: "application/json",
        headers: {
            "token":token
        },
        url: "http://localhost:2082/user/page?current=" + current,
        success: function(data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if(responseToken == "overdue"){
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                //操作成功
                if(result.code == 200){
                    const pageData = result.data;
                    //records：获取到的分页数组数据
                    const records = eval("("+JSON.stringify(pageData)+")").records;
                    //total：所有数据的数量
                    const total = eval("("+JSON.stringify(pageData)+")").total;
                    //size：每页数据的数量
                    const size = eval("("+JSON.stringify(pageData)+")").size;
                    //current：当前页数
                    const current = eval("("+JSON.stringify(pageData)+")").current;
                    //总页数
                    const pageNum = eval("("+JSON.stringify(pageData)+")").pages;

                    //初始化底部分页框
                    $("#userTotalPage").empty();
                    $("#userTotalPage").html(pageNum);
                    $("#userPageSelect").empty();
                    for (let i = 0; i < pageNum; i++) {
                        const pageValue = i + 1;
                        if(current === pageValue){
                            $("#userPageSelect").append("<option value='"+pageValue+"' selected>"+pageValue+"</option>");
                        }else {
                            $("#userPageSelect").append("<option value='"+pageValue+"'>"+pageValue+"</option>");
                        }
                    }

                    //先清空数据
                    for (let i = 1; i <= 10; i++) {
                        $("#userId" + i).empty();
                        $("#username" + i).empty();
                        $("#password" + i).empty();
                        $("#sex" + i).empty();
                        $("#phone" + i).empty();
                        $("#email" + i).empty();
                    }
                    //再进行赋值
                    let userNum;
                    if( (total-size*(current-1)) >= 10){
                        userNum = 10;
                    }else if( (total-size*(current-1)) < 10){
                        userNum = total-size*(current-1);
                        for (let i = userNum + 1; i <= 10; i++) {
                            //添加不可见样式
                            $("#userRow" + i).attr("style","display:none");
                        }
                    }
                    for (let i = 1; i <= userNum; i++) {
                        //移除不可见样式
                        $("#userRow" + i).removeAttr("style");
                        let userId = JSON.stringify(records[i-1].userId);
                        let username = JSON.stringify(records[i-1].username);
                        let password = JSON.stringify(records[i-1].password);
                        let sex = JSON.stringify(records[i-1].sex);
                        let phone = JSON.stringify(records[i-1].phone);
                        let email = JSON.stringify(records[i-1].email);
                        if(userId == null){
                            userId = "/";
                        }
                        if(username == null){
                            username = "/";
                        }
                        if(password == null){
                            password = "/";
                        }
                        if(sex == null){
                            sex = "/";
                        }
                        if(phone == null){
                            phone = "/";
                        }
                        if(email == null){
                            email = "/";
                        }
                        $("#userId" + i).html(userId.replace(/\"/g, ""));
                        $("#username" + i).html(username.replace(/\"/g, ""));
                        $("#password" + i).html(password.replace(/\"/g, ""));
                        $("#sex" + i).html(sex.replace(/\"/g, ""));
                        $("#phone" + i).html(phone.replace(/\"/g, ""));
                        $("#email" + i).html(email.replace(/\"/g, ""));
                    }
                }
                //操作失败
                else if(result.code == 500){
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}

//添加用户ajax
function addUserAjax(token,user){
    $.ajax({
        type: "POST",
        contentType: "application/json",
        headers: {
            "token":token
        },
        data: JSON.stringify(user),
        url: "http://localhost:2082/user",
        success: function(data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if(responseToken == "overdue"){
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                //操作成功
                if(result.code == 200){
                    $("#addUser").modal('hide');
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "success",
                        autoclose: 2000
                    });
                    //再进行一次分页操作
                    const current = $("#userPageSelect option:selected").text();
                    pageUserAjax(token,current);
                }
                //操作失败
                else if(result.code == 500){
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}

//获取某一个用户的信息ajax
function getOneUserAjax(token,username){
    $.ajax({
        type: "GET",
        contentType: "application/json",
        headers: {
            "token":token
        },
        url: "http://localhost:2082/user/one?username=" + username,
        success: function(data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if(responseToken == "overdue"){
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                //操作成功
                if(result.code == 200){
                    const userData = result.data;
                    const username = eval("("+JSON.stringify(userData)+")").username;
                    const password = eval("("+JSON.stringify(userData)+")").password;
                    const sex = eval("("+JSON.stringify(userData)+")").sex;
                    const birthday = eval("("+JSON.stringify(userData)+")").birthday;
                    const phone = eval("("+JSON.stringify(userData)+")").phone;
                    const email = eval("("+JSON.stringify(userData)+")").email;

                    //先清空修改用户弹出框中的内容
                    $("#updateUsername").val("");
                    $("#updatePassword").val("");
                    $("#updateSex").find('option[value="男"]').prop('selected',true);
                    $("#updateBirthday").val("");
                    $("#updatePhone").val("");
                    $("#updateEmail").val("");

                    //再对修改用户弹出框进行赋值
                    $("#updateUsername").val(username);
                    $("#updatePassword").val(password);
                    if(sex == "男"){
                        $("#updateSex").find('option[value="男"]').prop('selected',true);
                    }else {
                        $("#updateSex").find('option[value="女"]').prop('selected',true);
                    }
                    $("#updateBirthday").val(birthday);
                    $("#updatePhone").val(phone);
                    $("#updateEmail").val(email);
                }
                //操作失败
                else if(result.code == 500){
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}

//修改用户信息ajax
function updateUserAjax(token,user,isUpdateUsername){
    $.ajax({
        type: "PATCH",
        contentType: "application/json",
        headers: {
            "token":token
        },
        data: JSON.stringify(user),
        url: "http://localhost:2082/user?isUpdateUsername=" + isUpdateUsername,
        success: function(data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if(responseToken == "overdue"){
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                //操作成功
                if(result.code == 200){
                    $("#reviseUser").modal("hide");
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "success",
                        autoclose: 2000
                    });
                    //再进行一次分页操作
                    const current = $("#userPageSelect option:selected").text();
                    pageUserAjax(token,current);
                }
                //操作失败
                else if(result.code == 500){
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}

//删除用户ajax
function deleteUserAjax(token,userId){
    $.ajax({
        type: "DELETE",
        contentType: "application/json",
        headers: {
            "token":token
        },
        url: "http://localhost:2082/user?userId=" + userId,
        success: function(data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if(responseToken == "overdue"){
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                //操作成功
                if(result.code == 200){
                    $("#deleteUser").modal('hide');
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "success",
                        autoclose: 2000
                    });
                    //再进行一次分页操作
                    const current = $("#userPageSelect option:selected").text();
                    pageUserAjax(token,current);
                }
                //操作失败
                else if(result.code == 500){
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}

//修改管理员密码ajax
function updateAdminPassword(token,oldPassword,newPassword){
    $.ajax({
        type: "PATCH",
        contentType: "application/json",
        headers: {
            "token":token
        },
        url: "http://localhost:2082/user/admin/password?oldPassword=" + oldPassword + "&newPassword=" + newPassword,
        success: function(data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if(responseToken == "overdue"){
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                //操作成功
                if(result.code == 200){
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "success",
                        autoclose: 2000
                    });
                    const oldPassword = $("#oldPassword").val("");
                    const newPassword = $("#newPassword").val("");
                    const reNewPassword = $("#reNewPassword").val("");
                }
                //操作失败
                else if(result.code == 500){
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}

//根据用户名模糊查询用户信息ajax
function searchByUsernameAjax(token,username){
    $.ajax({
        type: "GET",
        contentType: "application/json",
        headers: {
            "token":token
        },
        url: "http://localhost:2082/user/like?username=" + username,
        success: function(data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if(responseToken == "overdue"){
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                //操作成功
                if(result.code == 200){
                    const pageData = result.data;
                    //records：获取到的分页数组数据
                    const records = eval("("+JSON.stringify(pageData)+")").records;
                    //total：所有数据的数量
                    const total = eval("("+JSON.stringify(pageData)+")").total;
                    //size：每页数据的数量
                    const size = eval("("+JSON.stringify(pageData)+")").size;
                    //current：当前页数
                    const current = eval("("+JSON.stringify(pageData)+")").current;
                    //总页数
                    const pageNum = eval("("+JSON.stringify(pageData)+")").pages;

                    //初始化底部分页框
                    $("#userTotalPage").empty();
                    $("#userTotalPage").html(pageNum);
                    $("#userPageSelect").empty();
                    for (let i = 0; i < pageNum; i++) {
                        const pageValue = i + 1;
                        if(current === pageValue){
                            $("#userPageSelect").append("<option value='"+pageValue+"' selected>"+pageValue+"</option>");
                        }else {
                            $("#userPageSelect").append("<option value='"+pageValue+"'>"+pageValue+"</option>");
                        }
                    }

                    //先清空数据
                    for (let i = 1; i <= 10; i++) {
                        $("#username" + i).empty();
                        $("#password" + i).empty();
                        $("#sex" + i).empty();
                        $("#phone" + i).empty();
                        $("#email" + i).empty();
                    }
                    //再进行赋值
                    let userNum;
                    if( (total-size*(current-1)) >= 10){
                        userNum = 10;
                    }else if( (total-size*(current-1)) < 10){
                        userNum = total-size*(current-1);
                        for (let i = userNum + 1; i <= 10; i++) {
                            //添加不可见样式
                            $("#userRow" + i).attr("style","display:none");
                        }
                    }
                    for (let i = 1; i <= userNum; i++) {
                        //移除不可见样式
                        $("#userRow" + i).removeAttr("style");
                        let username = JSON.stringify(records[i-1].username);
                        let password = JSON.stringify(records[i-1].password);
                        let sex = JSON.stringify(records[i-1].sex);
                        let phone = JSON.stringify(records[i-1].phone);
                        let email = JSON.stringify(records[i-1].email);
                        if(username == null){
                            username = "/";
                        }
                        if(password == null){
                            password = "/";
                        }
                        if(sex == null){
                            sex = "/";
                        }
                        if(phone == null){
                            phone = "/";
                        }
                        if(email == null){
                            email = "/";
                        }
                        $("#username" + i).html(username.replace(/\"/g, ""));
                        $("#password" + i).html(password.replace(/\"/g, ""));
                        $("#sex" + i).html(sex.replace(/\"/g, ""));
                        $("#phone" + i).html(phone.replace(/\"/g, ""));
                        $("#email" + i).html(email.replace(/\"/g, ""));
                    }
                }
                //操作失败
                else if(result.code == 500){
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}